<?php
namespace Peas\Kernel;

use Peas\Config\Configure;
use Peas\Database\Db;
use Peas\Database\DbLink;
use Peas\Cache\Cache;

/**
 * Peas Framework
 *
 * 数据层基类
 *
 * @author  Hongzan Zhang <zhanghongzan@163.com>
 * @version $Id$
 */
class Dao
{
    /**
     * 数据库连接
     *
     * @var array
     */
    private static $_links = [];

    /**
     * 数据库ID
     *
     * @var int
     */
    protected $_linkId = 0;

    /**
     * 数据库连接
     *
     * @var \Peas\Database\DbLink
     */
    protected $_link = null;


    /**
     * 初始化连接
     */
    public function __construct()
    {
        $this->_link = $this->getLinkById($this->_linkId);
    }

    /**
     * 根据数据库ID获取连接
     *
     * @param  int $linkId
     * @return \Peas\Database\DbLink
     */
    public function getLinkById($linkId)
    {
        if ($linkId == 0) {
            return Db::getLink();
        }
        $key = '_link_' . $linkId;
        if (key_exists($key, self::$_links)) {
            return self::$_links[$key];
        }
        $newLink = new DbLink(Configure::get($key));
        $cacheConfig = Configure::get($key . '.cache');
        if (!empty($cacheConfig)) {
            $newLink->setCacheInstance(Cache::getNewStore($cacheConfig));
        }
        self::$_links[$key] = $newLink;
        return $newLink;
    }
}
